import React, { useEffect, useMemo, useState } from 'react'
import ApplySearch from '../../components/Apply/ApplySearch'
import { Button, Divider, Popover, Segmented, Table, ConfigProvider, } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN'
import { DownOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { getApplt, setAppltStatus } from '../../apis/apply';
import ExportJsonExcel from 'js-export-excel'
import type { FilterValue, SorterResult } from 'antd/es/table/interface';

type Props = {}

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
  filters?: Record<string, FilterValue>;
}


const Apply = (props: Props) => {
  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const columns: ColumnsType<DataType> = [
    {
      title: 'id',
      dataIndex: 'id',
    },
    {
      title: '商铺名称',
      dataIndex: 'shopName',
    },
    {
      title: '手机号码',
      dataIndex: 'tel',
    },
    {
      title: '地址',
      dataIndex: 'address',
    },
    {
      title: '申请人姓名',
      dataIndex: 'managerName',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      filters: [
        { text: '同意', value: '同意' },
        { text: '拒绝', value: '拒绝' },
        { text: '审核中', value: '审核中' },
      ],
      onFilter: (value: any, record: any) => record.status.indexOf(value) === 0,
      filterMultiple: false
    },
    {
      title: '营业执照编号',
      dataIndex: 'licenceNo',
    },
    {
      title: '营业执照',
      dataIndex: 'licenceImg',
      render: (text, val: any) => (
        <img src={val?.licenceImg} alt="" style={{ width: '30px' }} />
      )
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, val: any) => (
        val.status == '审核中' ?
          <div>
            <div><Button onClick={() => agreeBtn(val)}>同意</Button></div>
            <div><Button onClick={() => refuse(val)}>拒绝</Button></div>
          </div> : null

      )
    },
  ];

  //导出表格的方法，只看方法
  const downloadFileToExcel = () => {
    const datas = data.length != 0 ? data : '';//表格数据
    // console.log('datas',datas);

    var option: any = {};
    let dataTable: any = [];
    if (datas) {
      datas.map((item: any) => {
        let obj = {
          id: item.id,
          shopName: item.shopName,
          tel: item.tel,
          managerName: item.managerName,
          address: item.address,
          idCard: item.idCard,
          status: item.status,
          licenceNo: item.licenceNo,
          licenceImg: item.licenceImg,
        }
        dataTable.push(obj);
        return dataTable
      })

    }
    option.id = 'ID'
    option.fileName = 'Apply列表'
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: 'Apply',
        sheetFilter: ['id', 'shopName', 'tel', 'address', 'managerName', 'idCard', 'status', 'licenceNo', 'licenceImg'],
        sheetHeader: ['id', '商铺名称', '手机号码', '地址', '申请人姓名', '身份证号', '审核状态', '营业执照编号', '营业执照'],
      }
    ];
    var toExcel = new ExportJsonExcel(option);
    console.log('toExcel', toExcel);

    toExcel.saveExcel();
  }

  useEffect(() => {
    getAppltData()
  }, [])

  //同意审核
  const agreeBtn = async (val: any) => {
    console.log(val);
    const res = await setAppltStatus({
      id: val.id,
      shopName: val.shopName,
      tel: val.tel,
      address: val.address,
      managerName: val.managerName,
      idCard: val.idCard,
      licenceNo: val.licenceNo,
      status: '同意'
    })
    console.log(res);
    getAppltData()
  }

  //拒绝审核
  const refuse = async (val: any) => {
    const res = await setAppltStatus({
      id: val.id,
      shopName: val.shopName,
      tel: val.tel,
      address: val.address,
      managerName: val.managerName,
      idCard: val.idCard,
      licenceNo: val.licenceNo,
      status: '拒绝'
    })
    console.log(res);
    getAppltData()
  }

  const getAppltData = async (val?: any) => {
    const res = await getApplt(val)
    console.log(res);
    if (res.status === 200) {
      setData(res.data.rows)
      setTotal(res.data.total)
    }
  }

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };


  const content = (
    <Button style={{ border: '0px' }} onClick={downloadFileToExcel}>导出Excel</Button>
  );


  const [showArrow, setShowArrow] = useState(true);
  const [arrowAtCenter, setArrowAtCenter] = useState(false);

  const mergedArrow = useMemo<any>(() => {
    if (arrowAtCenter) return { pointAtCenter: true };
    return showArrow;
  }, [showArrow, arrowAtCenter]);

  const getSeaData = (val: any) => {
    console.log(val);
    getAppltData(val)
  }

  //获取页数和当前页
  const updatePage = (val: any) => {
    console.log('val', val);
    const data = {
      pageNum: val.current,
      pageSize: val.pageSize
    }
    getAppltData(data)
  }

  //重置
  const resetting = () => {
    getAppltData()
  }

  return (
    <div>
      {/* 搜索 */}
      <div>
        <ApplySearch getSeaData={getSeaData} resetting={resetting}></ApplySearch>
      </div>

      <div style={{ marginLeft: '40px' }}>
        <Popover placement="bottom" content={content} arrow={mergedArrow}>
          <Button>更多操作 <DownOutlined /></Button>
        </Popover>
      </div>

      {/* 表单 */}
      <div style={{ marginTop: '20px' }}>
        <ConfigProvider locale={zh_CN}>
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data}
            rowKey='id'
            pagination={{ total: total, pageSizeOptions: [10, 20, 50, 100], showQuickJumper: true, showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条记录, 共 ${total} 条数据` }} onChange={updatePage}
          />
        </ConfigProvider>
      </div>

    </div>
  )
}

export default Apply